const app = getApp();
import http from '../utils/request'

let service = http.create({
  baseURL: app.globalData.BaseURL
})

/**
 * 多个请求合并
 * @param {Array} arr 
 */
const requestAll = (arr) => {
  return http.all(arr)
}

/**
 * 
 * @param {*} url 
 * @param {*} method 
 * @param {Object} data 参数
 * @param {Object} header 请求头
 */
const request = (url, method, data, personType) => {
  const _method = method.toLowerCase()
  let token = personType ? wx.getStorageSync('userToken') : wx.getStorageSync('staffToken')
  return new Promise((resolve, reject) => {
    service[_method](url, {
      data: data ? data : '',
      header: {
        // token: token,
        Authorization: token
      }
    }).then(res => {
     
      resolve(res)
    }).catch(error => {
      reject(error)
    })
  })
}
/**
 * 请求拦截器
 */
service.interceptors.request.use(
  config => {
    // const token = wx.getStorageSync('token')
    // config.header['Authorization'] = "Bearer " + token
    // config.header['token'] = token
    config.header['content-type'] = "application/x-www-form-urlencoded"
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
/**
 * 响应拦截器
 */
service.interceptors.response.use(
  response => {
    if (response.data.resultCode != 0) {
      console.log('请求失败', response)
      // 此处可添加错误处理
      // wx.showToast({
      //   title: '请求失败',
      // })
      if (response.data.resultCode == '1001') {
        wx.showToast({
          title: "您的认证情况已更新，请重新授权登录",
          icon: 'none',
          duration: 2000
        })
      }
      if(response.data.errorMsg=="对不起，您的账号已被锁定。"){
        wx.showToast({
          title: response.data.errorMsg,
          icon: 'none',
          duration: 2000
        })
        wx.removeStorageSync('userToken')
        wx.removeStorageSync('userInfor')
      }
      if (response.data.msg == "请先登录") {
        wx.showToast({
          title: 'token失效，请重新授权信息！',
          icon: 'none',
          duration: 2000
        })
        wx.hideLoading({
          complete: (res) => {
            wx.removeStorage({
              key: 'token',
            })
            wx.reLaunch({
              url: '/pages/index/index',
            })
          },
        })


      }
      Promise.reject(new Error(response.data.msg || 'Error'));
      return response.data;
    }
    console.log('请求成功', response.data)
    return response.data
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

module.exports = {
  request,
  requestAll
}